package com.gray.blog.interceptor;

import com.gray.blog.common.annotation.IpCheckTrigger;
import com.gray.blog.common.enums.ErrorCodeEnum;
import com.gray.blog.common.util.IpAddressUtil;
import com.gray.blog.common.util.JoinPointUtil;
import com.gray.blog.common.util.ResultUtil;
import com.gray.blog.entity.sys.IpBlackListEntity;
import com.gray.blog.interceptor.pointcut.ControllerPointCut;
import com.gray.blog.service.IpBlackListService;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Created  By zhoux 2018/10/29
 **/
@Slf4j
@Aspect
@Order(1)
@Component
public class IpInterceptor extends ControllerPointCut {

    @Autowired
    private IpBlackListService ipBlackListService;

    @Around("controllerMethod()")
    public Object ipInterceptor(ProceedingJoinPoint joinPoint) throws Throwable {
        Method method = JoinPointUtil.ProceedingJoinPoint2Method(joinPoint);
        Object result = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        if (method == null) {
            log.info("IpInterceptor.IpInterceptor method is null");
        } else {
            IpCheckTrigger ipCheckTrigger = method.getAnnotation(IpCheckTrigger.class);
            if (ipCheckTrigger != null) {
                String ip = IpAddressUtil.getIpAddress(request);
                IpBlackListEntity ipBlackListEntity = ipBlackListService.getIpBlackInfoByIp(ip);
                if (ipBlackListEntity != null) {
                    // 黑名单数据
                    log.warn("IpInterceptor.IpInterceptor ip in the black list ip:{}", ip);
                    ResultUtil.buildErrorResult(ErrorCodeEnum.IP_IS_DISABLED, response);
                    return null;
                }
            }
        }
        result = joinPoint.proceed();
        return result;
    }

}
